#!/bin/bash
#set -x

#####
# Cron job script to check hushitong health care system processes. It is installed as by cron job script by install-rc-cron.sh.
# If any of the processes is dead this script will start it.
#####

if [ -f /opt/hushitong/logs/hst-app-monitor.60.log ]; then
  rm -rf /opt/hushitong/logs/hst-app-monitor.60.log
fi
let num=59
while (( num>=1 ))
do
  let num_next=num+1
  if (( num==9 )); then
    if [ -f /opt/hushitong/logs/hst-app-monitor.0${num}.log ]; then
      mv /opt/hushitong/logs/hst-app-monitor.0${num}.log /opt/hushitong/logs/hst-app-monitor.${num_next}.log
    fi
  elif (( num<9 )); then
    if [ -f /opt/hushitong/logs/hst-app-monitor.0${num}.log ]; then
      mv /opt/hushitong/logs/hst-app-monitor.0${num}.log /opt/hushitong/logs/hst-app-monitor.0${num_next}.log
    fi
  else 
    if [ -f /opt/hushitong/logs/hst-app-monitor.${num}.log ]; then
      mv /opt/hushitong/logs/hst-app-monitor.${num}.log /opt/hushitong/logs/hst-app-monitor.${num_next}.log
    fi
  fi
  (( num-- ))
done

file_name=/opt/hushitong/logs/hst-app-monitor.01.log

echo "Application status at "`date` > $file_name

tpid=`ps -ef|grep prometheus|grep -v grep|grep -v kill| grep "config\.file=" | awk '{print $2}'`
if [ "${tpid}" ]; then
  echo 'INFO: Process prometheus is running.' >> $file_name
else
  echo 'ERROR: Process prometheus is NOT running. Restarting...' >> $file_name
  /opt/hushitong/prometheus/prometheus --config.file="/opt/hushitong/prometheus/prometheus.yml" --storage.tsdb.retention=1d --storage.tsdb.path="/opt/hushitong/prometheus/data" &
fi

tpid=`ps -ef|grep keycloak|grep -v grep|grep -v kill| grep -v standalone.sh | grep java | awk '{print $2}'`
if [ "${tpid}" ]; then
  echo 'INFO: Process keycloak is running.' >> $file_name
else
  echo 'ERROR: Process keycloak is NOT running. Restarting...' >> $file_name
  /opt/hushitong/keycloak/bin/standalone.sh &
fi

tpid=`ps -ef|grep datarest|grep -v grep|grep -v kill| grep "Process=datarest" | grep java | awk '{print $2}'`
if [ "${tpid}" ]; then
  echo "INFO: Process datarest is running." >> $file_name
else
  echo "ERROR: Process datarest is NOT running. Restarting..." >> $file_name
  /opt/hushitong/datarest/launchServer.sh
fi
  
tpid=`ps -ef|grep webserver|grep -v grep|grep -v kill| grep "Process=webserver" | grep java | awk '{print $2}'`
if [ "${tpid}" ]; then
  echo 'INFO: Process webserver is running.' >> $file_name
else
  echo 'ERROR: Process webserver is NOT running. Restarting...' >> $file_name
  /opt/hushitong/webserver/launchServer.sh
fi

uptime >> $file_name
top -b -n 1 >> $file_name
free >> $file_name
ps -ef | grep java >> $file_name
